package com.bookmarket.controller;

import com.bookmarket.entity.Admin;
import com.bookmarket.service.HJHLoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/backstagelogin")
public class HJHBackstageLoginController {

    @Resource
    private HJHLoginService hJHLoginServices;


    @RequestMapping("/loginAdmin")
    public String login(Admin admin, Model model, HttpSession session){
        ModelAndView mv=new ModelAndView();
        Subject subject = SecurityUtils.getSubject() ;
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getName(),admin.getPass()) ;

        try {
            subject.login(token);
            session.setAttribute("admin",admin);
            return "forward:/backstage/index1.jsp" ;
        }catch (Exception e){
            //这里将异常打印关闭是因为如果登录失败的话会自动抛异常
//            e.printStackTrace();
            model.addAttribute("error","用户名或密码错误") ;
            return "redirect:/backstage/adminLogin.ftl" ;
        }
    }

    /*@RequestMapping("/admin")
    public String admin(){
        return "forward:/backstage/index1.jsp";
    }

    @RequestMapping("/student")
    public String student(){
        return "forward:/backstage/index1.jsp" ;
    }

    @RequestMapping("/teacher")
    public String teacher(){
        return "forward:/backstage/index1.jsp" ;
    }
*/

    @RequestMapping("/findRole")
    public ModelAndView findRole(String name){
        ModelAndView mv=new ModelAndView();
        int role_id=hJHLoginServices.findRole_id(name);
        String role=hJHLoginServices.findRole(role_id);
        mv.addObject("role",role);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

    @RequestMapping("/logout")
    public ModelAndView logout(HttpSession session){
        ModelAndView mv=new ModelAndView();
        session.removeAttribute("admin");
        //mv.setViewName("forward:/backstage/index1.jsp");
        mv.setViewName("forward:/backstage/adminLogin.ftl");
        return mv;
    }

    @RequestMapping("/tologin")
    public ModelAndView tologin(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("redirect:/backstage/adminLogin.ftl");
        return mv;
    }


    public HJHLoginService gethJHLoginServices() {
        return hJHLoginServices;
    }

    public void sethJHLoginServices(HJHLoginService hJHLoginServices) {
        this.hJHLoginServices = hJHLoginServices;
    }
}